﻿using Microsoft.Extensions.Primitives;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SendMailServer.Jike
{
    internal class JikeFileGetter
    {
        public static string jkDir = "D:\\agcimDesktopFiles\\AgCIM技术月刊\\jikepages";
        public JikeFileGetter() {
        }
        public ResMsg LoadJikeFile(string key,string filterStr)
        {
            if (key != "GetJikeFileList")
            {
                return null;
            }
            if (filterStr == null) { filterStr = ""; }
            if (filterStr.EndsWith(",desktop"))
            {
                filterStr = filterStr.Substring(0, filterStr.Length - ",desktop".Length);
            }
            var filters = filterStr.Split('&');
            var includeFilterFiles=new List<string>();
            for(var i=0; i<filters.Length; i++)
            {
                if (filters[i].StartsWith("tag="))
                {
                    var filterNames=ExamHelper.SearchJikeTagData(filters[i].Substring(4));
                    if (filterNames.Length > 0)
                    {
                        filterNames = filterNames.TrimEnd('#');
                        includeFilterFiles.AddRange(filterNames.Split('#'));
                    }
                }
            }
            var files = new DirectoryInfo(jkDir).GetFiles("*.html", SearchOption.AllDirectories);
            StringBuilder stringBuilder = new StringBuilder();
            for (var i = 0; i < files.Length; i++)
            {
                if(includeFilterFiles.Count>0&& includeFilterFiles.IndexOf(Path.GetFileNameWithoutExtension(files[i].Name)) < 0)
                {
                    continue;
                }
                if (stringBuilder.Length > 0)
                {
                    stringBuilder.Append(",");
                }
                var relativePath = files[i].FullName.Substring(jkDir.Length).Trim(new char[] { '/','\\' });
                var createTime = files[i].CreationTime;
                stringBuilder.Append(relativePath);
                stringBuilder.Append("*");
                stringBuilder.Append(createTime);
            }
            return new ResMsg()
            {
                MsgCode = key,
                IsOk = true,
                Content = stringBuilder.ToString(),
                UseSelfResponse = true
            };
        }
    }
}
